package com.weibotwo.web.controller;

import com.weibotwo.common.Exception.UserServiceException;
import com.weibotwo.common.util.FaceFormat;
import com.weibotwo.common.util.PageResult;
import com.weibotwo.pojo.User;
import com.weibotwo.service.UserService;
import com.weibotwo.service.WeiBoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UserController
 * @Author 天火
 * @Date 2019-02-28
 * @Version 1.0
 */
@Controller
public class UserController {

    /**
     * 视图配置
     */
    private ModelAndView modelAndView = new ModelAndView();

    private PageResult pageResult = new PageResult();

    @Autowired
    private UserService userService;

    @Autowired
    private WeiBoService weiBoService;


    /**
     * 登录成功跳转至用户个人首页
     */
    @RequestMapping("/login_action")
    public ModelAndView login_index(String userid, String password, String save, HttpSession session, HttpServletResponse response) {

        modelAndView.clear();
        try {
            User loginUser = userService.login(userid, password);
            session.setAttribute("loginUser", loginUser);        //将登陆用户信息保存在session中
            modelAndView.setViewName("redirect:home");

            if (save != null) {
                Cookie emailCookie = new Cookie("weibo_email", userid);
                emailCookie.setMaxAge(30 * 60);    //设置cookie过期时间为7天
                Cookie pwdCookie = new Cookie("weibo_password", password);
                pwdCookie.setMaxAge(30 * 60);
                response.addCookie(pwdCookie);
                response.addCookie(emailCookie);
            }

            if (save != null) {
                Cookie emailCookie = new Cookie("weibo_email", userid);
                emailCookie.setMaxAge(24 * 60 * 30);    //设置cookie过期时间为7天
                Cookie pwdCookie = new Cookie("weibo_password", password);
                pwdCookie.setMaxAge(24 * 60 * 10);
                response.addCookie(pwdCookie);
                response.addCookie(emailCookie);
            }
            Map<String, Object> alerts = userService.alerts(loginUser.getId());
            session.setAttribute("alerts", alerts);

        } catch (UserServiceException e) {
            modelAndView.setViewName("login");
            modelAndView.addObject("msg", e.getMessage());
            return modelAndView;
        }
        return modelAndView;
    }

    /**
     * 个人信息主页
     *
     * @param session
     * @param pageNum
     * @return
     */
    @RequestMapping("/profile")
    public ModelAndView profile_index(HttpSession session, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,String action) {
        modelAndView.setViewName("user/profile");
        User user;
        user = (User) session.getAttribute("loginUser");
        try {
            if (user == null) {
                modelAndView.setViewName("login");
                return modelAndView;
            }

            PageResult result = userService.findWeiboListByUserId(user.getId(), pageNum, 10,action);
            List<User> userTuiJian = weiBoService.findTuijianById(user.getId());
            modelAndView.addObject("tuijian", userTuiJian);
            modelAndView.addObject("weiboList", result.getRows());
            modelAndView.addObject("totalPage", pageResult.getPageTotals());
            modelAndView.addObject("pageNum", pageNum);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return modelAndView;
    }

    /**
     * 功能：实现注册功能，在emailServlet方法中已经对用户输入的邮箱地址做了验证
     * 因此不必在该方法中做验证，直接调用service层中的register方法将用户信息保
     * 存到数据库中
     * @param user SpringMVC中如果参数的名称跟控制器方法参数中声明的类中的属
     * 性对应，就可以自动实例
     * @return
     */
    @RequestMapping("registerAction")
    public ModelAndView registerUser(User user){
        modelAndView.clear();
        try {
            if(user.getSex().equals("1")){
                //用户性别为男，修改初始化头像
                user.setImages("face/boy.png");
            }else if(user.getSex().equals("0")){
                //用户性别为女时
                user.setImages("face/gril.png");
            }
            userService.register(user);
            modelAndView.setViewName("register");
            modelAndView.addObject("msg", "注册成功");
        } catch (Exception e) {
            modelAndView.setViewName("register");
            modelAndView.addObject("msg", e.getMessage());
        }
        return modelAndView;
    }

    /**
     * 功能 : 判断用户输入的邮箱是否已被注册，使用邮箱作为用户的唯一标识
     * 		作为接受前端发来异步请求接受的方法，查询数据库中邮箱地址为
     * 		用户输入的email的用户，如果存在，就返回显示错误的图片和
     * 		邮箱已被注册的文字，如果该email不存在，则返回正确的图片和
     * @param resp HttpServletResponse响应
     * @param email	异步请求所携带的用户输入的邮箱
     * @return
     */
    @RequestMapping("registerServlet")		//判断用户输入的邮箱是否已被注册
    public ModelAndView emailServlet(HttpServletResponse resp,String email){
        modelAndView.clear();
        try {
            User user = userService.findUserByEmail(email);
            resp.setContentType("text");
            PrintWriter pw = null;
            pw = resp.getWriter();
            if(user==null){
                pw.print("<img src='icon/ok.png' align='absmiddle'> ");
            }else{
                pw.print("<img src='icon/err.png' align='absmiddle'> <font color='red'>邮箱已被注册</font>");
            }
            pw.flush();
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新用户信息
     *
     * @param session
     * @param user
     * @param year
     * @param month
     * @param day
     * @return
     */
    @RequestMapping(value = "userInfoUpdate", method = RequestMethod.POST)
    public ModelAndView userInfoUpdate(HttpSession session, User user, String year, String month, String day) {
        modelAndView.clear();
        String birthday = year + "-" + month + "-" + day;        //拼接生日
        User loginUser = (User) session.getAttribute("loginUser");        //获取登陆用户
        if(loginUser == null){
            modelAndView.setViewName("login");
            modelAndView.addObject("msg","未登录");
            return modelAndView;
        }
        loginUser.setNickName(user.getNickName());
        loginUser.setName(user.getName());
        loginUser.setSex(user.getSex());
        loginUser.setSign(user.getSign());
        loginUser.setPosition(user.getPosition());
        loginUser.setBirthday(birthday);
        session.setAttribute("loginUser", loginUser);
        try {
            userService.updateUser(loginUser);
            modelAndView.addObject("msg", "修改成功！");
        } catch (Exception e) {
            modelAndView.addObject("msg", e.getMessage());
        }
        modelAndView.setViewName("forward:userInfoIndex");
        return modelAndView;
    }

    /**
     * 保存新密码
     */
    @RequestMapping("/updatePassword")
    public ModelAndView updateUserPassword(HttpSession session, String newPassword) {
        modelAndView.clear();
        modelAndView.setViewName("user/password");
        User user = (User) session.getAttribute("loginUser");
        try {
            String passwordMD5 = DigestUtils.md5DigestAsHex(newPassword.getBytes());
            user.setPassword(passwordMD5);
            userService.updateUser(user);
            session.setAttribute("loginUser", user);
            modelAndView.addObject("msg", "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    /**
     * 密保问题更新
     */
    @RequestMapping("/updateQuestion")
    public ModelAndView updateQuestion(HttpSession session, String newQuestion, String newAnswer) {
        modelAndView.clear();
        User user = (User) session.getAttribute("loginUser");
        user.setPwdQuestion(newQuestion);
        user.setPwdAnswer(newAnswer);
        try {
            userService.updateUser(user);
            session.setAttribute("loginUser", user);
            modelAndView.setViewName("forward:questionIndex");
            modelAndView.addObject("msg", "修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    /**
     * 头像更新
     * @param icon
     * @param session
     * @param request
     * @return
     */
    @RequestMapping("/updateFace")
    public ModelAndView updateFace(@RequestParam("icon") MultipartFile icon, HttpSession session, HttpServletRequest request) {

        modelAndView.clear();
        modelAndView.setViewName("user/face");
        User user = (User) session.getAttribute("loginUser");
        if (!(icon.isEmpty())) {    //如果文件存在，isEmpty文件为空
            //保存文件目录
            String path = request.getSession().getServletContext().getRealPath("/") + "WEB-INF/jsp/face/" + user.getId() + ".jpg";
            File newFile = new File(path);
            //判断文件目录存在不存在，如果不存在就创建目录
            if (!(newFile.getParentFile().exists())) {
                newFile.getParentFile().mkdirs();
            }
            try {
                icon.transferTo(newFile);    //转存文件

                File oldIcon = new File(request.getSession().getServletContext().getRealPath("/") + "WEB-INF/jsp/" + user.getImages());    //删除之前的头像
                if (!(user.getImages().equals("face/boy.png") || user.getImages().equals("face/girl.png"))) {
                    //先判断用户之前的头像不是系统默认的头像，然后删除用户之前的头像
                    if (oldIcon.exists()) {
                        oldIcon.delete();
                    }
                }
                user.setImages("face/" + user.getId() + ".jpg");
                userService.updateUser(user);    //保存用户头像
                session.setAttribute("loginUser", user);    //将保存后的用户头像信息保存在用户session中
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            modelAndView.addObject("msg", "图片不存在");
        }
        return modelAndView;
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @RequestMapping("/exit")
    public String exit(HttpSession session) {
        session.removeAttribute("loginUser");
        session.removeAttribute("alerts");
        return "login";
    }

    @RequestMapping("forget")
    public ModelAndView forget(String email) {
        modelAndView.clear();
        try {
            User user = userService.findUserByEmail(email);
            if (user == null) {
                //用户不存在的
                modelAndView.setViewName("register");
                modelAndView.addObject("msg", "该用户不存在！");
            } else {
                //用户存在
                modelAndView.setViewName("forget");
                modelAndView.addObject("fUser", user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return modelAndView;
    }


    //********************************Ajax请求***************************************************//


    /**
     * 密码验证
     *
     * @param session
     * @param response
     * @param pwd
     * @return
     */
    @RequestMapping("/passwordApprove")
    public ModelAndView pwd(HttpSession session, HttpServletResponse response, String pwd) {
        modelAndView.clear();
        try {
            User user = (User) session.getAttribute("loginUser");

            String passwordMD5 = DigestUtils.md5DigestAsHex(pwd.getBytes());
            if (user == null) {
                modelAndView.setViewName("../login");
                return modelAndView;
            }
            response.setContentType("text");
            PrintWriter pw = null;
            pw = response.getWriter();
            if (user.getPassword().equals(passwordMD5)) {
                pw.print("<img src='icon/ok.png' align='absmiddle'> ");
            } else {
                pw.print("<img src='icon/err.png' align='absmiddle'> <font color='red'>密码错误</font>");
            }
            pw.flush();
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 密保问题验证
     *
     * @param session
     * @param answer   打哪
     * @param response res
     * @return ModelAndView
     */
    @RequestMapping("/questionApprove")
    public ModelAndView QAServlet(HttpSession session, String answer, HttpServletResponse response) {
        modelAndView.clear();
        User user = (User) session.getAttribute("loginUser");
        try {
            if (user == null) {
                modelAndView.setViewName("../login");
                return modelAndView;
            }
            response.setContentType("text");
            PrintWriter pw = response.getWriter();
            if (user.getPwdAnswer().equals(answer)) {
                pw.print("<img src='icon/ok.png' align='absmiddle'> ");
            } else {
                pw.print("<img src='icon/err.png' align='absmiddle'> <font color='red'>答案错误</font>");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 重置密码
     *
     * @param email 邮箱
     * @return modelAndView
     */
    @RequestMapping(value = "passwordReset", method = RequestMethod.POST)
    public ModelAndView up_forget(String email, User fuser, HttpSession session) {
        modelAndView.clear();
        try {
            User auser = userService.findUserByEmail(email);
            if (auser.getPwdAnswer().equals(fuser.getPwdAnswer())) {
                //修改用户登陆密码
                String passwordMD5 = DigestUtils.md5DigestAsHex(fuser.getPassword().getBytes());
                auser.setPassword(passwordMD5);
                userService.updateUser(auser);
                modelAndView.setViewName("register");
                modelAndView.addObject("msg", "密码重置成功！");
            } else {
                modelAndView.setViewName("redirect:forget");
                modelAndView.addObject("email", email);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    /**
     * 验证密保答案
     *
     * @param email
     * @param answer
     * @param resp
     * @return
     */
    @RequestMapping("forgetAnswer")
    public ModelAndView forgetAnswer(String email, String answer, HttpServletResponse resp) {
        try {
            User user = userService.findUserByEmail(email);

            resp.setContentType("text");
            PrintWriter pw = resp.getWriter();
            if (user.getPwdAnswer().equals(answer)) {
                pw.print("<img src='icon/ok.png' align='absmiddle'> ");
                modelAndView.addObject("answer", "true");
            } else {
                pw.print("<img src='icon/err.png' align='absmiddle'> <font color='red'>答案错误</font>");
            }
            pw.flush();
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    @RequestMapping("collect")
    public ModelAndView collectIndex(HttpSession session, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        modelAndView.clear();
        modelAndView.setViewName("user/collect");
        User user = (User) session.getAttribute("loginUser");


        try {
            if(user==null){
                modelAndView.setViewName("login");
                return modelAndView;
            }
            PageResult result = userService.findCollectWeiboByUserId(user.getId(), pageNum);
            result.setRows(FaceFormat.formt(result.getRows()));

            List<User> userTuiJian = weiBoService.findTuijianById(user.getId());
            modelAndView.addObject("tuijian", userTuiJian);
            modelAndView.addObject("weiboList", result.getRows());
            modelAndView.addObject("pageNum", pageNum);
            modelAndView.addObject("totalPage", pageResult.getPageTotals());
            session.setAttribute("action", "collect");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }
}




